import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import {
  Form,
  Input,
  InputNumber,
  Select,
  Button, Space, Switch, Tooltip,
} from 'antd'
import {t, Trans} from "@lingui/macro"
import {MinusCircleOutlined, PlusOutlined} from "@ant-design/icons";
import ItemSwitch from './ItemSwitch'
import TextArea from 'antd/es/input/TextArea'
const FormItem = Form.Item
const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
}

/**
 * 扩展字段提示
 */
const tips = {
  frontType: "前端显示组件类型",
  frontName: "前端显示的名称；主要是补充不规范表命名导致的表现力不足",
  javaType: "字段对应后端显示的数据类型； 默认低代码引擎自动推断",
  uploadCount: "允许上传的文件数量",
  ignoreInList: "忽略该字段在列表页显示",
  foreign: "字段对应的外键； 主要是用来做select,treeSelect;举例：other_table.id~title",
  option: "选项；用来配置字段键值对；格式: 0:禁用,1:启用",
  isFilter: "字段是否出现在列表页搜索框",
}

//扩展项配置
const extendFileds = {
  frontType: {name: '前端类型', tip: "前端显示组件类型", valueType: 'select'},
  frontName: {name: "前端名字", tip:"前端显示的名称；主要是补充不规范表命名导致的表现力不足", valueType: 'input'},
  javaType: {name: "Java类型", tip: "字段对应后端显示的数据类型； 默认低代码引擎自动推断", valueType: 'select'},
  uploadCount: {name: "上传文件数", tip: "允许上传的文件数量", valueType: 'number'},
  ignoreInList: {name: "列表隐藏", tip: "忽略该字段在列表页显示", valueType: 'switch'},
  foreign: {name: "外键", tip: "字段对应的外键； 主要是用来做select,treeSelect;举例：other_table.id~title", valueType: 'input'},
  option: {name:"选项", tip: "选项；用来配置字段键值对；格式: 0:禁用,1:启用; 默认为： null", valueType: 'input'},
  isFilter: {name: "搜索项", tip: "字段是否出现在列表页搜索框; 默认为: false", valueType: 'switch'},
  isApproval: {name: "审核字段", tip: "该字段是否出现在审批信息中; 默认为: false", valueType: 'switch'},
  editReadOnly: {name:"只读字段", tip: "在编辑框是否为只读， 默认: false", valueType: 'switch'},
  editHidden: {name:"编辑隐藏", tip: "在编辑框是否显示， 默认: false", valueType: 'switch'},
  isEnum: {name:"枚举字段", tip: "该字段是否为枚举字段，主要是后端生成枚举类， 默认: null", valueType: 'switch'},
  linkDetails: {name:"关联详情", tip: "该字段是否关联详情， 默认: false", valueType: 'switch'},
  dict: {name:"字典", tip: "该字段是否为字典，主要是后端生成字典接口， 默认: null", valueType: 'input'}
}

class CodeTableColumnModal extends PureComponent {
  formRef = React.createRef()

  state = {
    value: [],
    loading: false, //上传 loading
    optionNames:{}, //选项选中值
    extendItems: [], //解析的值
  };

  constructor(props) {
    super(props);
    // 初始化扩展信息
    const {item} = props;
    const extendItems = this.parseExtendItems(item)
    const names = extendItems.map(value => {
      return value.name;
    })
    this.state.optionNames = names;
    this.state.extendItems = extendItems
  }


  handleOk = () => {
    const { item = {}, onOk, onClose } = this.props
    this.formRef.current.validateFields()
      .then(values => {
        const data = {
          ...values,
          id: item.id,
          //时间值处理
        }

        let comment = "";
        let optionStr = ""
        values.optionItems && values.optionItems.map((v,k)=>{
          if(v.name == "option") {
            optionStr = v.value
          } else {
            comment += v.name + ":" + v.value
            if(k != (values.optionItems.length - 1)) {
              comment += ","
            }
          }
        })
        comment = (values.title ? values.title : "") +";"+optionStr+";" + comment
        data.comment = comment
        delete data.optionItems
        // console.log("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
        // console.log(data)
        onOk(data)
      })
      .catch(errorInfo => {
        console.log(errorInfo)
      })
  }

  /**
   * 解析扩展数据
   *
   * @param item
   * @returns {[]}
   */
  parseExtendItems = (item) => {
    let comment = item.comment
    let title = item.title;
    let extendOptions = ""
    let extendItems = []
    if(comment) {
      let parts = comment.split(";")
      if(parts.length>0) {
        //   //title
        title = parts[0]
        if(parts.length>=2) {
          extendOptions = parts[1]
        }
        if(parts.length>=3) {
          let extendParts = parts[2].split(",")
          for(let i=0; i<extendParts.length; i++) {
            let tmpParts = extendParts[i].split(":")
            console.log(extendParts[i])
            if(tmpParts.length==2) {
              //检查处理值类型
              if(extendFileds[tmpParts[0]] && extendFileds[tmpParts[0]].valueType == 'switch') {
                extendItems.push({name: tmpParts[0], value: tmpParts[1] == 'true' ? true : false})
              } else {
                extendItems.push({name: tmpParts[0], value: tmpParts[1]})
              }
            }
          }
        }
      }
    }
    //检查填充option
    if(extendOptions && extendOptions != "") {
      extendItems.push({name:'option', value: extendOptions})
    }
    return extendItems;
  }

  /**
   * props更新时候更换数据触发
   *
   * @param prevProps
   */
  componentDidUpdate(prevProps) {
    // id为空则说明为创建， 不要重新解析避免丢失表单信息
    if (prevProps?.item?.id !== this.props?.item?.id ) {
      const { item } = this.props;
      let extendItems = this.parseExtendItems(item);
      let values = this.formRef.current.getFieldsValue();
      let initData = {}
      for(let name in values) {
        initData[name] = null;
      }
      initData = { ...initData, ...item };
      initData['optionItems'] = extendItems;
      let optionNames = {};
      for (let i = 0; i < extendItems.length; i++) {
        optionNames[i] = extendItems[i].name;
      }
      this.setState({ optionNames: { ...optionNames }, extendItems: extendItems });
      this.formRef.current.resetFields();
      this.formRef.current.setFieldsValue(initData);
    }
  }

  render() {
    const { item = {}, onOk,onClose, form,options,trees, ...modalProps } = this.props

    const dataTypeOptionData = Object.keys(options.dataType).map((k,index)=>{
      return {value: k, label: options.dataType[k]}
    })

    //处理解析扩展项数据
    let extendItems = this.state.extendItems;
    let initData = {...item};
    initData['optionItems'] = extendItems;
    //初始化title
    if(!item.title) {
      let comment = item.comment;
      if(comment) {
        let parts = comment.split(";")
        if(parts.length>0) {
          initData.title = parts[0]
        }
      }
    }

    //初始化时间处理
    return (
        <Form ref={this.formRef} name="control-ref" initialValues={{ ...initData }} layout="horizontal" labelCol={{span: 8}} wrapperCol={{span: 16}} onFinish={this.handleOk}>
          <FormItem  name='name' rules={[{ required: false }]}
                     label={t`Name`} hasFeedback {...formItemLayout}>
            <Input maxLength={45} />
          </FormItem>
          <FormItem  name='title' rules={[{ required: false }]}
                     label={t`Title`} hasFeedback {...formItemLayout}>
            <Input maxLength={45} />
          </FormItem>
          <FormItem  name='dataType' rules={[{ required: false }]}
                     label={t`Data Type`} hasFeedback {...formItemLayout}>
            <Select
              showSearch
              placeholder={t`Data Type`}
              optionFilterProp="children"
              options={dataTypeOptionData}
            />
          </FormItem>
          <FormItem  name='length' rules={[{ required: false }]}
                     label={t`Length`} hasFeedback {...formItemLayout}>
            <InputNumber max={99999999999}  style={{width:200}} />
          </FormItem>
          <FormItem  name='isPk' rules={[{ required: false }]}
                     label={t`Is Pk`} hasFeedback {...formItemLayout}>
            <ItemSwitch />
          </FormItem>
          <FormItem  name='isNotNull' rules={[{ required: false }]}
                     label={t`Is Not Null`} hasFeedback {...formItemLayout}>
            <ItemSwitch />
          </FormItem>
          <FormItem  name='isUnique' rules={[{ required: false }]}
                     label={t`Is Unique`} hasFeedback {...formItemLayout}>
            <ItemSwitch />
          </FormItem>
          <FormItem  name='isAutoIncrement' rules={[{ required: false }]}
                     label={t`Is Auto Increment`} hasFeedback {...formItemLayout}>
            <ItemSwitch />
          </FormItem>
          <FormItem  name='isZeroFill' rules={[{ required: false }]}
                     label={t`Is Zero Fill`} hasFeedback {...formItemLayout}>
            <ItemSwitch />
          </FormItem>
          <FormItem  name='defaultValue' rules={[{ required: false }]}
                     label={t`Default Value`} hasFeedback {...formItemLayout}>
            <Input maxLength={1000} />
          </FormItem>
          <FormItem  name='scale' rules={[{ required: false }]}
                     label={t`Scale`} hasFeedback {...formItemLayout}>
            <InputNumber max={99999999999}  style={{width:200}} />
          </FormItem>
          <FormItem  name='comment' rules={[{ required: false }]}
                     label={t`Comment`} hasFeedback {...formItemLayout}>
            <TextArea maxLength={1024} />
          </FormItem>

          <FormItem  name='extend' rules={[{ required: false }]}
                     label={t`Extend Data`} hasFeedback {...formItemLayout}>
            <Form.List name="optionItems" style={{margin: "350px"}} rules={[{required: false}]} hasFeedback >
              {(fields, { add, remove }) => (

                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space key={key} style={{ display: 'flex', marginBottom: 2 }} size={"small"} align="baseline">
                      <Form.Item
                        {...restField}
                        name={[name, 'name']}
                        rules={[{required: false}]} >
                        <Select
                          placeholder={"请选择扩展项名称"}
                          onChange={(e)=>{
                            let optionNames = this.state.optionNames
                            optionNames[key] = e
                            this.setState({...this.state, optionNames: optionNames})
                          }}>
                          {Object.keys(extendFileds).map((item) =>{
                            return <Select.Option value={item}>{extendFileds[item].name}</Select.Option>
                          })}
                        </Select>
                      </Form.Item>
                      {/*java类型选择*/}
                      {this.state.optionNames[key] && this.state.optionNames[key]=="javaType" && <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        // style={{width: 100}}
                        rules={[{required: false}]} >
                        <Select placeholder={"请选择Java类型"} style={{width: '300px'}}>
                          <Select.Option value={"Long"}>Long</Select.Option>
                          <Select.Option value={"Integer"}>Integer</Select.Option>
                          <Select.Option value={"Boolean"}>Boolean</Select.Option>
                          <Select.Option value={"String"}>String</Select.Option>
                          <Select.Option value={"LocalDatetime"}>LocalDatetime</Select.Option>
                          <Select.Option value={"Date"}>Date</Select.Option>
                        </Select>
                      </Form.Item>}
                      {/*frontType选择*/}
                      {this.state.optionNames[key] && this.state.optionNames[key]=="frontType" && <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        // style={{width: 100}}
                        rules={[{required: false}]} >
                        <Select placeholder={"请选择前端类型"}  style={{width: '300px'}}>
                          <Select.Option value="text">Text</Select.Option>
                          <Select.Option value="select">Select</Select.Option>
                          <Select.Option value="treeSelect">TreeSelect</Select.Option>
                          <Select.Option value="checkbox">Checkbox</Select.Option>
                          <Select.Option value="textarea">Textarea</Select.Option>
                          <Select.Option value="editor">editor</Select.Option>
                          <Select.Option value="datetime">datetime</Select.Option>
                          <Select.Option value="date">date</Select.Option>
                          <Select.Option value="upload">upload</Select.Option>
                          <Select.Option value="number">number</Select.Option>
                          <Select.Option value="password">password</Select.Option>
                        </Select>
                      </Form.Item>}
                      {/*uploadSize  Number*/}
                      {this.state.optionNames[key] &&
                        // this.state.optionNames[key]=="uploadCount"
                        extendFileds[this.state.optionNames[key]]?.valueType == "number"
                        && <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        style={{width: 100}}
                        rules={[{required: false}]} >
                        <InputNumber defaultValue={1} value={1} />
                      </Form.Item>}

                      {this.state.optionNames[key] && (
                        // this.state.optionNames[key]=="foreign"
                        // || this.state.optionNames[key]=="parent"
                        // || this.state.optionNames[key]=="frontName"
                        // // || this.state.optionNames[key]=="foreign"
                        // // || this.state.optionNames[key]=="tree"
                        // || this.state.optionNames[key]=="option"
                        extendFileds[this.state.optionNames[key]]?.valueType == "input"
                      ) && <Tooltip {...{trigger: "hover",placement: 'bottomLeft',color:"red", title:tips[this.state.optionNames[key]] || ''}} ><Form.Item
                                      {...restField}
                                      name={[name, 'value']}
                                      // style={{width: 100}}
                                      rules={[{required: false}]} >
                            <Input style={{width: '300px'}} />
                      </Form.Item></Tooltip>}
                      {/*Bool Select*/}
                      {this.state.optionNames[key] && (
                        // this.state.optionNames[key]=="isFilter"
                        // || this.state.optionNames[key]=="ignoreInList"
                        // || this.state.optionNames[key]=="isApproval"
                        // || this.state.optionNames[key]=="editReadOnly"
                        // || this.state.optionNames[key]=="isEnum"
                        // ||
                        extendFileds[this.state.optionNames[key]]?.valueType == "switch"
                      ) && <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        style={{width: 100}}
                        rules={[{required: false}]}
                        valuePropName="checked"
                      >
                        <Switch checkedChildren="是" unCheckedChildren="否" />
                      </Form.Item>}

                      {/*{this.state.optionNames[key] &&*/}
                      {/*  this.state.optionNames[key]=="frontHome" && <Form.Item*/}
                      {/*  {...restField}*/}
                      {/*  name={[name, 'value']}*/}
                      {/*  style={{width: 100}}*/}
                      {/*  rules={[{required: false}]} >*/}
                      {/*  <Select defaultValue={"list"}>*/}
                      {/*    <Select.Option value={"list"}>List</Select.Option>*/}
                      {/*    <Select.Option value={"tree"}>Tree</Select.Option>*/}
                      {/*  </Select>*/}
                      {/*</Form.Item>}*/}


                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  ))}

                  <Form.Item>
                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                      {/*Add Extend Data Item*/}
                      添加扩展项
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </FormItem>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit" onClick={()=>{
                this.handleOk();
              }}>
                {t`Submit`}
              </Button>
              <Button htmlType="button" onClick={()=>{
                onClose();
              }}>
                {t`Close`}
              </Button>
            </Space>

          </Form.Item>

        </Form>
      // </Modal>
    )
  }
}

CodeTableColumnModal.propTypes = {
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
}

export default CodeTableColumnModal

